﻿using System;
using System.Configuration;
using ECommerce.SchemaGenerator.Properties;
using ECommerce.Web;
using ECommerce.Web.NHibernate;
using ECommerce.Web.NHibernate.ConfigurationBuilders;
using ECommerce.Web.NHibernate.Sessions;
using ECommerce.Web.SqlServer;
using NHibernate;
using NHibernateCfg = NHibernate.Cfg;

namespace ECommerce.SchemaGenerator
{
    internal class Program
    {        
        internal static void Main(string[] args)
        {
            Console.WriteLine("Generating database schema...");
            
            ExportSchema();

            RunSqlScripts();
        }

        private static void ExportSchema()
        {
            NHibernateCfg.Configuration configuration = GetNHibernateConfiguration();

            Bootstrapper.ConfigureSessionSource(configuration);

            ISession session = SessionSource.Current.GetSession();

            var exporter = new SchemaExporter(configuration);

            exporter.Export(session.Connection);

            SessionSource.Current.CloseSession();
        }

        private static NHibernateCfg.Configuration GetNHibernateConfiguration()
        {
            var configurationBuilder = new DefaultConfigurationBuilder();

            return configurationBuilder.Build(PersistenceOptions.Default());
        }

        private static void RunSqlScripts()
        {
            string connectionString = GetConnectionString();

            SqlServerScriptRunner scriptRunner = new SqlServerScriptRunner(connectionString);

            scriptRunner.RunScriptsInFolder(Settings.Default.SqlScriptsFolderPath);
        }

        private static string GetConnectionString()
        {
            return ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        }
    }
}
